package com.hzyb.oldpack.controller;

import com.alibaba.fastjson.JSONObject;
import com.hzyb.oldpack.model.HzybConfig;
import com.hzyb.oldpack.service.HzybConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/WechatPayment")
public class WechatPaymentController {


    @Value("${Wechat.apiUrl}")
    private String apiUrl;

    private final static Logger Logger = LoggerFactory.getLogger(WechatPaymentController.class);

    private static final String grant_type = "authorization_code";

    @Resource
    private HzybConfigService hzybConfigService;

    @Resource
    private HttpSession HttpSession;

    @RequestMapping("/getOpenid")
    public Map<String, Object> getOpenid(@RequestParam String userCode, @RequestParam String appid) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", "fail");
        try {
            List<HzybConfig> hzybConfig = hzybConfigService.getByAppid(appid);
            if (null == hzybConfig || hzybConfig.size() != 1) {
                map.put("errorMsg", "invalid appid");
                return map;
            }
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiUrl + "?appid=" + hzybConfig.get(0).getAppid() + "&js_code=" + userCode + "&secret="
                    + hzybConfig.get(0).getAppsecret() + "&grant_type=" + grant_type, String.class);
            Logger.info("apiUrl---" + apiUrl + "?appid=" + hzybConfig.get(0).getAppid() + "&js_code=" + userCode + "&secret="
                    + hzybConfig.get(0).getAppsecret() + "&grant_type=" + grant_type);
            JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
            map.put("openId", jsonObject.get("openid"));
            map.put("errcode", jsonObject.get("errcode"));
            map.put("errmsg", jsonObject.get("errmsg"));
            map.put("status", "success");
            HttpSession.setAttribute(jsonObject.get("openid").toString(), jsonObject.get("session_key"));
        } catch (Exception e) {
            // TODO: handle exception
            Logger.error(e.toString());
        }
        return map;
    }

}
